package com.gph.saviorframework.mq.api.bean;

import com.gph.saviorframework.mq.api.MQFactory;
import com.gph.saviorframework.mq.api.MessageListener;
import com.gph.saviorframework.mq.api.exception.MQClientException;
import com.gph.saviorframework.mq.api.order.MessageOrderListener;
import com.gph.saviorframework.mq.api.order.OrderConsumer;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * Created by root on 16-7-11.
 */
public class OrderConsumerBean implements OrderConsumer {

    private Properties properties;
    private Map<Subscription, MessageOrderListener> subscriptionTable;

    private OrderConsumer consumer;

    /**
     * 启动服务
     */
    public void start() {
        if (null == this.properties) {
            throw new MQClientException("properties not set");
        }

        if (null == this.subscriptionTable) {
            throw new MQClientException("subscriptionTable not set");
        }
        this.consumer = MQFactory.createOrderConsumer(properties);

        Iterator<Map.Entry<Subscription, MessageOrderListener>> it = this.subscriptionTable.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Subscription, MessageOrderListener> next = it.next();
            this.subscribe(next.getKey().getTopic(), next.getKey().getExpression(), next.getValue());
        }

        this.consumer.start();
    }

    /**
     * 关闭服务
     */
    public void shutdown() {
        if (this.consumer != null) {
            this.consumer.shutdown();
        }
    }

    /**
     * 订阅消息
     *
     * @param topic         消息主题
     * @param subExpression 订阅过滤表达式字符串，broker依据此表达式进行过滤。目前只支持或运算<br>
     *                      eg: "tag1 || tag2 || tag3"<br>
     *                      如果subExpression等于null或者*，则表示全部订阅
     * @param listener
     */
    public void subscribe(String topic, String subExpression, MessageOrderListener listener) {
        if (null == this.consumer) {
            throw new MQClientException("subscribe must be called after consumerBean started");
        }
        this.consumer.subscribe(topic, subExpression, listener);
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Map<Subscription, MessageOrderListener> getSubscriptionTable() {
        return subscriptionTable;
    }

    public void setSubscriptionTable(Map<Subscription, MessageOrderListener> subscriptionTable) {
        this.subscriptionTable = subscriptionTable;
    }

    public boolean isStarted() {
        return this.consumer.isStarted();
    }

    public boolean isClosed() {
        return this.consumer.isClosed();
    }
}
